using System;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class CallExpressionCodeGenerator
	{
		public static void GenerateBytecodeForList(Context ctx, Expression expr) {
			BuildCall(ctx, (CallExpression) expr);
		}
		
		public static void GenerateBytecodeForLocal(Context ctx, Expression expr, LocalBuilder lb) {
			BuildCall(ctx, (CallExpression) expr);
			CodeUtilities.MakeGetListValue(ctx.il, ctx.list, 0, lb);
			CodeUtilities.MakeClearList(ctx.il, ctx.list);
		}
		
		private static void BuildCall(Context ctx, CallExpression call) {
			LocalBuilder left = ctx.il.DeclareLocal(typeof(Value));
			call.left.GenerateBytecode(ctx, left);
			
			if (call.right != null)
				CodeGenerator.ParseRightList(ctx, call.right);
			
			ctx.il.Emit(OpCodes.Ldloc, left);
			ctx.il.Emit(OpCodes.Ldloc, ctx.list);
			ctx.il.Emit(OpCodes.Callvirt, typeof(Value).GetMethod("Invoke"));
		}
	}
}

